package com.bcurtu.amigo.services;

import java.math.BigInteger;

public class GroupIdEncrypter {

	public static String encode(Integer id) throws EncodingException{
		
		if (id<0) throw new EncodingException();
		
		int rnd=(int)(Math.random()*100);
		if (rnd<10) rnd=rnd+10;
		if (rnd==100) rnd--;
		
		int core=id*rnd;
		int body=Integer.parseInt(core+""+rnd);
		int crc=(body%89)+10;
		String s=crc+""+body;
		String total=Long.toHexString(Long.parseLong(s)).toUpperCase();
//		System.out.println("ENCODING:id="+id+",rnd="+rnd+",core="+core+",body="+body+",crc="+crc+",dec="+s+",hex="+total);
		return total;
	}
	
	public static Integer decode(String s) throws EncodingException{
		
		String dec=""+Long.decode("0x"+s);
		Integer crc=Integer.parseInt(dec.substring(0,2));
		Integer body=Integer.parseInt(dec.substring(2));
		Integer core=Integer.parseInt(dec.substring(2,dec.length()-2));
		Integer rnd=Integer.parseInt(dec.substring(dec.length()-2));

//		System.out.println("DECODING:rnd="+rnd+",core="+core+",body="+body+",crc="+crc+",dec="+dec+",hex="+s);

		if (((body%89)+10)!=crc) throw new EncodingException();

		int id=core/rnd;
		return id;
	}

	
}
